package com.to.aboomy.bannersample.viewpager.creator;

import com.to.aboomy.banner.HolderCreator;
import com.to.aboomy.banner.LogUtils;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Image;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.global.resource.WrongTypeException;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.io.IOException;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT;

/**
 * ImageHolde
 *
 * @since 2021-07-21
 */
public class ImageHolderCreator2 implements HolderCreator {
    @Override
    public Component createView(Context context, int integer, int index) {
        Image image = new Image(context);
        image.setScaleMode(Image.ScaleMode.STRETCH);
        image.setLayoutConfig(new ComponentContainer.LayoutConfig(MATCH_PARENT, MATCH_PARENT));
        try {
            ImageSource.SourceOptions options = new ImageSource.SourceOptions();
            options.formatHint = "image/jpg";
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            ResourceManager manager = context.getResourceManager();
            String path = manager.getMediaPath(integer);
            Resource r1 = manager.getRawFileEntry(path).openRawFile();
            ImageSource source = ImageSource.create(r1, options);
            PixelMap p1 = source.createPixelmap(decodingOptions);
            image.setPixelMap(p1);
        } catch (IOException e) {
            LogUtils.log(LogUtils.DEBUG,"IOException",e.getMessage());
        } catch (NotExistException e) {
            LogUtils.log(LogUtils.DEBUG,"NotExistException",e.getMessage());
        } catch (WrongTypeException e) {
            LogUtils.log(LogUtils.DEBUG,"WrongTypeException",e.getMessage());
        }
        return image;
    }
}